//this script is for using the average value of an arraylist to smooth a vector3

using UnityEngine;
using System.Collections;

public class SmoothTool : MonoBehaviour {
	
	//this number set how many number we use for smoothing.
	public int SmoothNumber;
	//this number count which position in array we insert the current position of keyjointID
	int SmoothCount=0;
	ArrayList SmoothArr=new ArrayList();
	
	static public float iota=0.000001f;
	// Use this for initialization
	void Start ()
	{
		for(int i=0;i<SmoothNumber;i++)
		{
			Vector3 pos=new Vector3(0,0,0);			
			SmoothArr.Add(pos);
		}		
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	public Vector3 GetFilteredValue()
	{
		Vector3 v=new Vector3(0,0,0);
		for(int i=0;i<SmoothArr.Count;i++)
		{
			v.x+=((Vector3)SmoothArr[i]).x;
			v.y+=((Vector3)SmoothArr[i]).y;
			v.z+=((Vector3)SmoothArr[i]).z;
		}
		v.x/=SmoothArr.Count;
		v.y/=SmoothArr.Count;
		v.z/=SmoothArr.Count;
		return v;		
	}
	
	//At the end of the smooth period, like when some guy get out of the detection period,
	//we must rewrite all the entried with zero.
	public void ClearAll()
	{
		for(int i=0;i<SmoothArr.Count;i++)
		{
			SmoothArr[i]=new Vector3(0,0,0);					
		}		
	}
	
	//this is a special function.
	//We do not only insert a Vector3 value, but also make some process during the first several frames of the smooth period
	//we will write all the Zero-value entry with the val , which is the current value.
	//Then we insert the val into (SmoothCount++)%SmoothNumber of arraylist
	//Pay attention to the way we compare the zero values.
	public void InsertValue(Vector3 val)
	{
		for(int i=0;i<SmoothArr.Count;i++)
	    {
			//when we detect a qualified player, if any vec in SmoothArr is zero, we set it the current position
			Vector3 tmpv=(Vector3)SmoothArr[i];
			if(
			   (Mathf.Abs(tmpv.x)<iota)&&
			   (Mathf.Abs(tmpv.y)<iota)&&
			   (Mathf.Abs(tmpv.z)<iota)
			  )
				{
					SmoothArr[i]=val;
				}						
		}	
		
		
		SmoothCount++;
		SmoothCount=SmoothCount%SmoothNumber;
		SmoothArr[SmoothCount]=val;	
		
	}
		
	
	
	
}
